package com.wenbo.fish.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wenbo.fish.dao.TouchFishDAO;
import com.wenbo.fish.entity.SpiderInfo;
import com.wenbo.fish.entity.TouchFish;
import com.wenbo.fish.utils.GsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author changwenbo
 * @date 2025/1/9 20:07
 */
@Slf4j
@Service
public class GetSpiderInfoService {

    @Autowired
    private TouchFishDAO touchFishDao;

    public List<SpiderInfo> getSpiderInfo(String name) {
        int maxCnt = getMaxCnt(name);
        LambdaQueryWrapper<TouchFish> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TouchFish::getType, name);
        wrapper.eq(TouchFish::getCnt, String.valueOf(maxCnt));
        wrapper.last(" order by id");
        List<TouchFish> touchFishList = touchFishDao.selectList(wrapper);
        log.info("getSpiderInfo name = {}, touchFishList = {}", name, GsonUtils.toJson(touchFishList.get(0)));
        return BeanUtil.copyToList(touchFishList, SpiderInfo.class);
    }

    private int getMaxCnt(String name) {
        try {
            LambdaQueryWrapper<TouchFish> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(TouchFish::getType, name);
            wrapper.last(" order by cnt desc limit 1");
            TouchFish touchFish = touchFishDao.selectOne(wrapper);
            if (touchFish != null && StringUtils.isNotEmpty(touchFish.getCnt())) {
                log.info("getMaxCnt name = {}, cnt = {}", name, touchFish.getCnt());
                return Integer.parseInt(touchFish.getCnt());
            }
        } catch (Exception e) {
            log.warn("getMaxCnt name = {}, e = {}", name, e.getMessage(), e);
        }
        return 1;
    }
}
